-- Lua Battle System - 错误处理框架
-- 实现全局错误捕获和处理机制

local Logger = require("utils.logger")
local Errors = require("utils.errors")
local EventSystem = require("utils.event_system")

local ErrorHandler = {
    -- 错误处理配置
    config = {
        enable_debug_info = true,
        enable_stack_trace = true,
        log_errors = true,
        trigger_events = true
    },
    
    -- 事件系统实例
    event_system = nil
}

-- 错误处理构造函数
function ErrorHandler:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化错误处理
function ErrorHandler:init()
    self.event_system = EventSystem:new()
    self:setup_global_error_handler()
    Logger.info("错误处理框架初始化完成")
end

-- 设置全局错误处理
function ErrorHandler:setup_global_error_handler()
    -- 保存原始的错误处理函数
    self.original_error_handler = debug.traceback
    
    -- 设置新的错误处理函数
    debug.traceback = function(message, level)
        return self:handle_error(message, level)
    end
    
    Logger.debug("全局错误处理已设置")
end

-- 处理错误
-- @param message 错误信息
-- @param level 错误级别
function ErrorHandler:handle_error(message, level)
    level = level or 2
    
    -- 获取堆栈跟踪
    local stack_trace = self.original_error_handler(message, level)
    
    -- 解析错误信息
    local error_obj = self:parse_error(message, stack_trace)
    
    -- 记录错误日志
    if self.config.log_errors then
        self:log_error(error_obj)
    end
    
    -- 触发错误事件
    if self.config.trigger_events then
        self.event_system:trigger("error", error_obj)
    end
    
    -- 返回格式化的错误信息
    return self:format_error_response(error_obj)
end

-- 解析错误信息
-- @param message 原始错误信息
-- @param stack_trace 堆栈跟踪
function ErrorHandler:parse_error(message, stack_trace)
    local error_type = Errors.SYSTEM_ERROR
    local details = {}

    -- 检查message是否为nil或空字符串
    if not message or message == "" then
        message = "未知错误"
    end

    -- 尝试从错误信息中提取错误类型
    for type_name, type_value in pairs(Errors.types) do
        if string.find(tostring(message), type_value) then
            error_type = type_value
            break
        end
    end

    -- 添加调试信息
    if self.config.enable_debug_info then
        details.raw_stack_trace = stack_trace
        details.timestamp = os.time()
        details.pid = tonumber(io.popen("echo %PID%", "r"):read("*l")) or -1

        -- 解析和增强堆栈跟踪
        details.enhanced_stack_trace = self:enhance_stack_trace(stack_trace)
        details.stack_summary = self:create_stack_summary(stack_trace)
    end

    -- 创建错误对象（带上下文）
    return Errors:create_with_context(error_type, message, details)
end

-- 增强堆栈跟踪信息
-- @param stack_trace 原始堆栈跟踪
-- @return 增强的堆栈跟踪信息
function ErrorHandler:enhance_stack_trace(stack_trace)
    if not stack_trace then
        return "无堆栈跟踪信息"
    end

    local enhanced = {}
    local lines = {}

    -- 分割堆栈跟踪行
    for line in stack_trace:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    for i, line in ipairs(lines) do
        if line ~= "" and line:find("stack traceback:") then
            table.insert(enhanced, line)
        elseif line:find("scripts/") or line:find("src/") then
            -- 解析文件路径和行号
            local file_path, line_num = line:match("(.+):(%d+):")
            if file_path and line_num then
                local function_name = line:match("in function '(.+)'") or "unknown"
                local enhanced_line = string.format("  [%d] %s:%d in %s", i-1, file_path, line_num, function_name)
                table.insert(enhanced, enhanced_line)
            else
                table.insert(enhanced, "  " .. line)
            end
        elseif line:find("C function") or line:find("tail call") then
            table.insert(enhanced, "  " .. line)
        end
    end

    return #enhanced > 0 and table.concat(enhanced, "\n") or stack_trace
end

-- 创建堆栈跟踪摘要
-- @param stack_trace 原始堆栈跟踪
-- @return 堆栈跟踪摘要
function ErrorHandler:create_stack_summary(stack_trace)
    if not stack_trace then
        return "无堆栈跟踪"
    end

    local summary = {
        functions = {},
        modules = {},
        deepest_call = nil,
        call_depth = 0
    }

    local lines = {}
    for line in stack_trace:gmatch("[^\r\n]+") do
        if line ~= "" and not line:find("stack traceback:") then
            table.insert(lines, line)
        end
    end

    summary.call_depth = #lines

    -- 分析每一行调用栈
    for _, line in ipairs(lines) do
        -- 提取函数名
        local func_name = line:match("in function '(.+)'")
        if func_name then
            table.insert(summary.functions, func_name)
        else
            table.insert(summary.functions, "anonymous")
        end

        -- 提取模块信息
        local module_path = line:match("src/([^:]+)")
        if module_path then
            local module_name = module_path:gsub("/", "."):gsub("%.lua", "")
            if not summary.modules[module_name] then
                summary.modules[module_name] = 0
            end
            summary.modules[module_name] = summary.modules[module_name] + 1
        end

        -- 记录最深层的调用
        if not summary.deepest_call then
            summary.deepest_call = line
        end
    end

    return summary
end

-- 获取调用栈中的关键信息
-- @param level 要分析的栈级别（默认为1，即调用者）
-- @return 调用信息表
function ErrorHandler:get_caller_info(level)
    level = level or 1

    local info = debug.getinfo(level + 1, "Slnt")
    if not info then
        return nil
    end

    return {
        source = info.source,
        short_src = info.short_src,
        linedefined = info.linedefined,
        currentline = info.currentline,
        name = info.name or "anonymous",
        what = info.what,
        namewhat = info.namewhat,
        istailcall = info.istailcall,
        nups = info.nups
    }
end

-- 获取完整的调用链
-- @param max_depth 最大深度（默认为10）
-- @return 调用链信息
function ErrorHandler:get_call_chain(max_depth)
    max_depth = max_depth or 10
    local chain = {}

    for level = 1, max_depth do
        local info = self:get_caller_info(level)
        if not info then
            break
        end

        table.insert(chain, {
            level = level,
            info = info,
            formatted = string.format("  [%d] %s:%d in %s()", level, info.short_src, info.currentline, info.name)
        })
    end

    return chain
end

-- 记录错误日志
-- @param error_obj 错误对象
function ErrorHandler:log_error(error_obj)
    local log_message = Errors:format(error_obj)

    -- 根据错误类型选择日志级别
    if error_obj.type == Errors.SYSTEM_ERROR or error_obj.type == Errors.INIT_ERROR then
        Logger.error("[FATAL] " .. log_message)  -- 使用error级别并添加FATAL标记
    elseif error_obj.type == Errors.CONFIG_ERROR or error_obj.type == Errors.BATTLE_ERROR then
        Logger.error(log_message)
    else
        Logger.warn(log_message)
    end
end

-- 格式化错误响应
-- @param error_obj 错误对象
function ErrorHandler:format_error_response(error_obj)
    local formatted = Errors:format_with_context(error_obj)

    if self.config.enable_stack_trace and error_obj.details then
        -- 添加增强的堆栈跟踪
        if error_obj.details.enhanced_stack_trace then
            formatted = formatted .. "\n\n增强堆栈跟踪:\n" .. error_obj.details.enhanced_stack_trace
        end

        -- 添加堆栈跟踪摘要
        if error_obj.details.stack_summary then
            local summary = error_obj.details.stack_summary
            if type(summary) == "table" then
                formatted = formatted .. string.format("\n\n堆栈摘要:\n")
                formatted = formatted .. string.format("  调用深度: %d\n", summary.call_depth)

                if #summary.functions > 0 then
                    formatted = formatted .. string.format("  调用函数: %s\n", table.concat(summary.functions, " -> "))
                end

                if next(summary.modules) then
                    local module_list = {}
                    for module, count in pairs(summary.modules) do
                        table.insert(module_list, string.format("%s(%d)", module, count))
                    end
                    formatted = formatted .. string.format("  涉及模块: %s\n", table.concat(module_list, ", "))
                end

                if summary.deepest_call then
                    formatted = formatted .. string.format("  最深层调用: %s\n", summary.deepest_call)
                end
            end
        end
    end

    return formatted
end

-- 捕获函数执行错误
-- @param func 要执行的函数
-- @param ... 函数参数
function ErrorHandler:capture_error(func, ...)
    local args = {...}
    
    local success, result = pcall(function() 
        return func(unpack(args))
    end)
    
    if not success then
        -- 处理错误
        local error_obj = self:parse_error(result, debug.traceback())
        
        if self.config.log_errors then
            self:log_error(error_obj)
        end
        
        if self.config.trigger_events then
            self.event_system:trigger("error", error_obj)
        end
        
        return false, error_obj
    end
    
    return true, result
end

-- 注册错误监听器
-- @param listener 监听器函数
-- @param priority 优先级
function ErrorHandler:register_error_listener(listener, priority)
    return self.event_system:register("error", listener, priority)
end

-- 移除错误监听器
-- @param listener 监听器函数
function ErrorHandler:remove_error_listener(listener)
    return self.event_system:unregister("error", listener)
end

-- 配置错误处理
-- @param config 配置选项
function ErrorHandler:configure(config)
    if config then
        for key, value in pairs(config) do
            if self.config[key] ~= nil then
                self.config[key] = value
            end
        end
        Logger.info("错误处理配置已更新")
    end
end

-- 错误恢复机制
local ErrorRecovery = {
    -- 恢复策略映射
    recovery_strategies = {},

    -- 恢复历史记录
    recovery_history = {},

    -- 最大重试次数
    max_retries = 3,

    -- 恢复延迟（毫秒）
    recovery_delay = 100
}

-- 注册错误恢复策略
-- @param error_type 错误类型
-- @param strategy 恢复策略函数
function ErrorHandler:register_recovery_strategy(error_type, strategy)
    if not ErrorRecovery.recovery_strategies[error_type] then
        ErrorRecovery.recovery_strategies[error_type] = {}
    end
    table.insert(ErrorRecovery.recovery_strategies[error_type], strategy)
end

-- 执行错误恢复
-- @param error_obj 错误对象
-- @param original_func 原始函数
-- @param ... 原始参数
-- @return 恢复结果
function ErrorHandler:attempt_recovery(error_obj, original_func, ...)
    local args = {...}
    local error_type = error_obj.type
    local strategies = ErrorRecovery.recovery_strategies[error_type]
    local unpack_func = unpack or table.unpack

    if not strategies or #strategies == 0 then
        -- 没有注册恢复策略，尝试默认恢复
        return self:default_recovery(error_obj, original_func, unpack_func(args))
    end

    -- 尝试每个注册的恢复策略
    for i, strategy in ipairs(strategies) do
        local success, result = pcall(strategy, error_obj, original_func, unpack_func(args))

        if success then
            -- 记录恢复成功
            self:record_recovery_attempt(error_obj, strategy, true, i)

            if result and result.success then
                return result
            end
        else
            -- 记录恢复失败
            self:record_recovery_attempt(error_obj, strategy, false, i, result)
        end
    end

    -- 所有策略都失败，返回失败
    return {
        success = false,
        error = "所有恢复策略都失败",
        original_error = error_obj
    }
end

-- 默认恢复策略
-- @param error_obj 错误对象
-- @param original_func 原始函数
-- @param ... 原始参数
function ErrorHandler:default_recovery(error_obj, original_func, ...)
    -- 根据错误类型执行默认恢复策略
    local error_type = error_obj.type

    if error_type == Errors.TIMEOUT_ERROR or error_type == Errors.NETWORK_ERROR then
        -- 重试策略
        return self:retry_operation(original_func, ...)
    elseif error_type == Errors.MEMORY_ERROR or error_type == Errors.RESOURCE_EXHAUSTED then
        -- 资源清理后重试
        collectgarbage("collect")
        return self:retry_operation(original_func, ...)
    elseif error_type == Errors.CONFIG_ERROR then
        -- 配置错误恢复
        return self:recover_from_config_error(error_obj, original_func, ...)
    elseif error_type == Errors.DATA_VALIDATION_FAILED or error_type == Errors.TYPE_MISMATCH then
        -- 数据错误恢复
        return self:recover_from_data_error(error_obj, original_func, ...)
    else
        -- 通用恢复策略
        return self:generic_recovery(error_obj, original_func, ...)
    end
end

-- 重试操作
-- @param func 要重试的函数
-- @param ... 函数参数
function ErrorHandler:retry_operation(func, ...)
    local args = {...}
    local last_error = nil
    local unpack_func = unpack or table.unpack

    for attempt = 1, ErrorRecovery.max_retries do
        -- 等待恢复延迟
        if attempt > 1 then
            os.execute("sleep " .. (ErrorRecovery.recovery_delay / 1000))
        end

        local success, result = pcall(func, unpack_func(args))

        if success then
            return {
                success = true,
                result = result,
                attempts = attempt,
                recovery_type = "retry"
            }
        else
            last_error = result
            Logger.warn(string.format("操作重试失败 (第%d次): %s", attempt, tostring(result)))
        end
    end

    return {
        success = false,
        error = "操作重试失败",
        last_error = last_error,
        attempts = ErrorRecovery.max_retries,
        recovery_type = "retry_failed"
    }
end

-- 配置错误恢复
-- @param error_obj 错误对象
-- @param original_func 原始函数
function ErrorHandler:recover_from_config_error(error_obj, original_func, ...)
    -- 尝试重新加载配置
    local success = pcall(function()
        -- 这里应该调用配置重新加载逻辑
        Logger.info("尝试重新加载配置文件")
    end)

    if success then
        return self:retry_operation(original_func, ...)
    else
        return {
            success = false,
            error = "配置重新加载失败",
            original_error = error_obj
        }
    end
end

-- 数据错误恢复
-- @param error_obj 错误对象
-- @param original_func 原始函数
function ErrorHandler:recover_from_data_error(error_obj, original_func, ...)
    -- 尝试清理和验证数据
    Logger.info("尝试数据恢复和验证")

    -- 数据验证和清理逻辑
    local success, result = pcall(function()
        -- 数据恢复逻辑
    end)

    if success then
        return self:retry_operation(original_func, ...)
    else
        return {
            success = false,
            error = "数据恢复失败",
            original_error = error_obj
        }
    end
end

-- 通用恢复策略
-- @param error_obj 错误对象
-- @param original_func 原始函数
function ErrorHandler:generic_recovery(error_obj, original_func, ...)
    -- 记录错误，但不重试
    Logger.warn("使用通用恢复策略，不进行重试")

    return {
        success = false,
        error = "通用恢复策略：已记录错误但不进行重试",
        original_error = error_obj,
        recovery_type = "generic"
    }
end

-- 记录恢复尝试
-- @param error_obj 错误对象
-- @param strategy 恢复策略
-- @param success 是否成功
-- @param attempt_count 尝试次数
-- @param error_message 错误信息（可选）
function ErrorHandler:record_recovery_attempt(error_obj, strategy, success, attempt_count, error_message)
    local record = {
        timestamp = os.time(),
        error_type = error_obj.type,
        error_message = error_obj.message,
        strategy = tostring(strategy),
        success = success,
        attempt_count = attempt_count,
        error_message = error_message
    }

    table.insert(ErrorRecovery.recovery_history, record)

    -- 限制历史记录数量
    if #ErrorRecovery.recovery_history > 1000 then
        table.remove(ErrorRecovery.recovery_history, 1)
    end

    if success then
        Logger.info(string.format("错误恢复成功: %s (尝试次数: %d)", error_obj.type, attempt_count))
    else
        Logger.warn(string.format("错误恢复失败: %s (尝试次数: %d, 错误: %s)",
                                error_obj.type, attempt_count, tostring(error_message)))
    end
end

-- 获取恢复历史
-- @param error_type 错误类型（可选）
-- @param limit 返回记录数量限制（可选）
-- @return 恢复历史记录
function ErrorHandler:get_recovery_history(error_type, limit)
    local history = ErrorRecovery.recovery_history

    if error_type then
        local filtered = {}
        for _, record in ipairs(history) do
            if record.error_type == error_type then
                table.insert(filtered, record)
            end
        end
        history = filtered
    end

    if limit and limit > 0 then
        local limited = {}
        local start = math.max(1, #history - limit + 1)
        for i = start, #history do
            table.insert(limited, history[i])
        end
        history = limited
    end

    return history
end

-- 安全执行函数（带恢复机制）
-- @param func 要执行的函数
-- @param recovery_context 恢复上下文（可选）
-- @param ... 函数参数
function ErrorHandler:safe_execute(func, recovery_context, ...)
    local args = {...}

    -- 兼容性处理：使用table.unpack或unpack
    local unpack_func = unpack or table.unpack

    -- 首先尝试正常执行
    local success, result = pcall(func, unpack_func(args))

    if success then
        return true, result
    else
        -- 执行失败，尝试错误恢复
        local error_obj = self:parse_error(result, debug.traceback())

        Logger.warn(string.format("函数执行失败，尝试错误恢复: %s", error_obj.type))

        local recovery_result = self:attempt_recovery(error_obj, func, unpack_func(args))

        if recovery_result.success then
            Logger.info("错误恢复成功")
            return true, recovery_result.result
        else
            Logger.error(string.format("错误恢复失败: %s", recovery_result.error))
            return false, recovery_result.original_error or error_obj
        end
    end
end

-- 性能监控器
local PerformanceMonitor = {
    -- 性能数据
    performance_data = {
        function_times = {},
        memory_usage = {},
        error_frequency = {},
        system_load = {}
    },

    -- 监控配置
    config = {
        enable_monitoring = true,
        sample_interval = 1000, -- 毫秒
        max_samples = 1000,
        memory_threshold = 50, -- MB
        response_time_threshold = 100 -- 毫秒
    },

    -- 性能计时器
    timers = {},

    -- 监控开始时间
    start_time = os.time()
}

-- 开始性能计时
-- @param timer_id 计时器ID
function ErrorHandler:start_performance_timer(timer_id)
    if not PerformanceMonitor.config.enable_monitoring then
        return
    end

    PerformanceMonitor.timers[timer_id] = {
        start_time = os.clock(),
        start_memory = collectgarbage("count"),
        context = Errors.ErrorContext.get_global_context()
    }
end

-- 结束性能计时
-- @param timer_id 计时器ID
-- @return 性能数据
function ErrorHandler:end_performance_timer(timer_id)
    if not PerformanceMonitor.config.enable_monitoring then
        return nil
    end

    local timer = PerformanceMonitor.timers[timer_id]
    if not timer then
        return nil
    end

    local end_time = os.clock()
    local end_memory = collectgarbage("count")

    local performance_data = {
        timer_id = timer_id,
        duration_ms = (end_time - timer.start_time) * 1000,
        memory_delta_kb = end_memory - timer.start_memory,
        start_memory_kb = timer.start_memory,
        end_memory_kb = end_memory,
        timestamp = os.time(),
        context = timer.context
    }

    -- 记录性能数据
    table.insert(PerformanceMonitor.performance_data.function_times, performance_data)

    -- 限制样本数量
    if #PerformanceMonitor.performance_data.function_times > PerformanceMonitor.config.max_samples then
        table.remove(PerformanceMonitor.performance_data.function_times, 1)
    end

    -- 检查性能阈值
    if performance_data.duration_ms > PerformanceMonitor.config.response_time_threshold then
        Logger.warn(string.format("性能警告: 函数 %s 执行时间过长 (%.2f ms)", timer_id, performance_data.duration_ms))
        self:trigger_performance_alert("slow_function", performance_data)
    end

    if performance_data.memory_delta_kb > 1024 then -- 1MB
        Logger.warn(string.format("内存警告: 函数 %s 内存增长过大 (%.2f KB)", timer_id, performance_data.memory_delta_kb))
        self:trigger_performance_alert("memory_leak", performance_data)
    end

    -- 清理计时器
    PerformanceMonitor.timers[timer_id] = nil

    return performance_data
end

-- 记录内存使用情况
function ErrorHandler:record_memory_usage()
    if not PerformanceMonitor.config.enable_monitoring then
        return
    end

    local memory_kb = collectgarbage("count")
    local memory_data = {
        timestamp = os.time(),
        memory_kb = memory_kb,
        memory_mb = memory_kb / 1024
    }

    table.insert(PerformanceMonitor.performance_data.memory_usage, memory_data)

    -- 限制样本数量
    if #PerformanceMonitor.performance_data.memory_usage > PerformanceMonitor.config.max_samples then
        table.remove(PerformanceMonitor.performance_data.memory_usage, 1)
    end

    -- 检查内存阈值
    if memory_data.memory_mb > PerformanceMonitor.config.memory_threshold then
        Logger.warn(string.format("内存警告: 系统内存使用过高 (%.2f MB)", memory_data.memory_mb))
        self:trigger_performance_alert("high_memory", memory_data)
    end
end

-- 触发性能告警
-- @param alert_type 告警类型
-- @param data 性能数据
function ErrorHandler:trigger_performance_alert(alert_type, data)
    local alert = {
        type = alert_type,
        timestamp = os.time(),
        data = data,
        severity = self:get_alert_severity(alert_type, data)
    }

    -- 触发性能告警事件
    if self.event_system then
        self.event_system:trigger("performance_alert", alert)
    end

    -- 记录告警
    Logger.warn(string.format("性能告警: %s - %s", alert_type, self:format_performance_alert(alert)))
end

-- 获取告警严重程度
-- @param alert_type 告警类型
-- @param data 性能数据
-- @return 严重程度
function ErrorHandler:get_alert_severity(alert_type, data)
    if alert_type == "high_memory" then
        if data.memory_mb > PerformanceMonitor.config.memory_threshold * 2 then
            return "critical"
        elseif data.memory_mb > PerformanceMonitor.config.memory_threshold * 1.5 then
            return "warning"
        else
            return "info"
        end
    elseif alert_type == "slow_function" then
        if data.duration_ms > PerformanceMonitor.config.response_time_threshold * 5 then
            return "critical"
        elseif data.duration_ms > PerformanceMonitor.config.response_time_threshold * 2 then
            return "warning"
        else
            return "info"
        end
    else
        return "warning"
    end
end

-- 格式化性能告警
-- @param alert 告警对象
-- @return 格式化的告警信息
function ErrorHandler:format_performance_alert(alert)
    if alert.type == "high_memory" then
        return string.format("内存使用过高: %.2f MB (阈值: %.2f MB)",
                            alert.data.memory_mb, PerformanceMonitor.config.memory_threshold)
    elseif alert.type == "slow_function" then
        return string.format("函数执行缓慢: %s 执行时间 %.2f ms (阈值: %d ms)",
                            alert.data.timer_id, alert.data.duration_ms, PerformanceMonitor.config.response_time_threshold)
    elseif alert.type == "memory_leak" then
        return string.format("疑似内存泄漏: %s 内存增长 %.2f KB",
                            alert.data.timer_id, alert.data.memory_delta_kb)
    else
        return string.format("未知性能告警: %s", alert.type)
    end
end

-- 记录错误频率
-- @param error_type 错误类型
function ErrorHandler:record_error_frequency(error_type)
    local current_time = os.time()
    local frequency_data = {
        timestamp = current_time,
        error_type = error_type
    }

    table.insert(PerformanceMonitor.performance_data.error_frequency, frequency_data)

    -- 限制样本数量
    if #PerformanceMonitor.performance_data.error_frequency > PerformanceMonitor.config.max_samples then
        table.remove(PerformanceMonitor.performance_data.error_frequency, 1)
    end

    -- 检查错误频率
    local recent_errors = self:get_recent_error_count(60) -- 最近60秒的错误
    if recent_errors > 10 then -- 阈值：60秒内超过10个错误
        Logger.warn(string.format("错误频率告警: 最近60秒内发生 %d 个错误", recent_errors))
        self:trigger_performance_alert("high_error_rate", {error_count = recent_errors, time_window = 60})
    end
end

-- 获取最近的错误数量
-- @param time_window_seconds 时间窗口（秒）
-- @return 错误数量
function ErrorHandler:get_recent_error_count(time_window_seconds)
    local current_time = os.time()
    local count = 0

    for _, error_data in ipairs(PerformanceMonitor.performance_data.error_frequency) do
        if current_time - error_data.timestamp <= time_window_seconds then
            count = count + 1
        end
    end

    return count
end

-- 获取性能统计报告
-- @return 性能统计报告
function ErrorHandler:get_performance_report()
    local report = {
        monitoring_enabled = PerformanceMonitor.config.enable_monitoring,
        monitoring_duration = os.time() - PerformanceMonitor.start_time,
        function_performance = {},
        memory_performance = {},
        error_statistics = {},
        alerts = {}
    }

    -- 函数性能统计
    if #PerformanceMonitor.performance_data.function_times > 0 then
        local durations = {}
        local memory_deltas = {}

        for _, data in ipairs(PerformanceMonitor.performance_data.function_times) do
            table.insert(durations, data.duration_ms)
            table.insert(memory_deltas, data.memory_delta_kb)
        end

        report.function_performance = {
            total_calls = #durations,
            avg_duration_ms = self:calculate_average(durations),
            max_duration_ms = self:calculate_max(durations),
            min_duration_ms = self:calculate_min(durations),
            avg_memory_delta_kb = self:calculate_average(memory_deltas),
            max_memory_delta_kb = self:calculate_max(memory_deltas),
            slow_functions = self:get_slow_functions(durations, PerformanceMonitor.performance_data.function_times)
        }
    end

    -- 内存性能统计
    if #PerformanceMonitor.performance_data.memory_usage > 0 then
        local memory_values = {}
        for _, data in ipairs(PerformanceMonitor.performance_data.memory_usage) do
            table.insert(memory_values, data.memory_kb)
        end

        report.memory_performance = {
            current_memory_kb = memory_values[#memory_values],
            avg_memory_kb = self:calculate_average(memory_values),
            max_memory_kb = self:calculate_max(memory_values),
            min_memory_kb = self:calculate_min(memory_values),
            memory_growth_kb = memory_values[#memory_values] - memory_values[1]
        }
    end

    -- 错误统计
    if #PerformanceMonitor.performance_data.error_frequency > 0 then
        local error_counts = {}
        for _, data in ipairs(PerformanceMonitor.performance_data.error_frequency) do
            error_counts[data.error_type] = (error_counts[data.error_type] or 0) + 1
        end

        report.error_statistics = {
            total_errors = #PerformanceMonitor.performance_data.error_frequency,
            error_types = error_counts,
            errors_per_hour = #PerformanceMonitor.performance_data.error_frequency / (report.monitoring_duration / 3600)
        }
    end

    return report
end

-- 计算平均值
-- @param values 数值数组
-- @return 平均值
function ErrorHandler:calculate_average(values)
    if #values == 0 then return 0 end

    local sum = 0
    for _, value in ipairs(values) do
        sum = sum + value
    end

    return sum / #values
end

-- 计算最大值
-- @param values 数值数组
-- @return 最大值
function ErrorHandler:calculate_max(values)
    if #values == 0 then return 0 end

    local max = values[1]
    for _, value in ipairs(values) do
        if value > max then
            max = value
        end
    end

    return max
end

-- 计算最小值
-- @param values 数值数组
-- @return 最小值
function ErrorHandler:calculate_min(values)
    if #values == 0 then return 0 end

    local min = values[1]
    for _, value in ipairs(values) do
        if value < min then
            min = value
        end
    end

    return min
end

-- 获取最慢的函数
-- @param durations 持续时间数组
-- @param performance_data 性能数据数组
-- @return 最慢的函数列表
function ErrorHandler:get_slow_functions(durations, performance_data)
    local slow_functions = {}
    local threshold = self:calculate_percentile(durations, 90) -- 90分位数

    for i, duration in ipairs(durations) do
        if duration >= threshold then
            table.insert(slow_functions, {
                timer_id = performance_data[i].timer_id,
                duration_ms = duration,
                timestamp = performance_data[i].timestamp
            })
        end
    end

    return slow_functions
end

-- 计算百分位数
-- @param values 数值数组
-- @param percentile 百分位数(0-100)
-- @return 百分位数值
function ErrorHandler:calculate_percentile(values, percentile)
    if #values == 0 then return 0 end

    -- 复制并排序数组
    local sorted = {}
    for _, value in ipairs(values) do
        table.insert(sorted, value)
    end
    table.sort(sorted)

    local index = math.ceil((percentile / 100) * #sorted)
    index = math.max(1, math.min(index, #sorted))

    return sorted[index]
end

-- 清理性能数据
function ErrorHandler:cleanup_performance_data()
    PerformanceMonitor.performance_data = {
        function_times = {},
        memory_usage = {},
        error_frequency = {},
        system_load = {}
    }
    PerformanceMonitor.timers = {}
    PerformanceMonitor.start_time = os.time()

    Logger.info("性能监控数据已清理")
end

-- 配置性能监控
-- @param config 监控配置
function ErrorHandler:configure_performance_monitoring(config)
    if config then
        for key, value in pairs(config) do
            if PerformanceMonitor.config[key] ~= nil then
                PerformanceMonitor.config[key] = value
            end
        end
        Logger.info("性能监控配置已更新")
    end
end

-- 获取错误统计信息
function ErrorHandler:get_error_stats()
    -- 统计错误类型
    local error_counts = {}
    local total_errors = 0
    local recovery_success_count = 0
    local recovery_failure_count = 0

    for _, record in ipairs(ErrorRecovery.recovery_history) do
        total_errors = total_errors + 1
        error_counts[record.error_type] = (error_counts[record.error_type] or 0) + 1

        if record.success then
            recovery_success_count = recovery_success_count + 1
        else
            recovery_failure_count = recovery_failure_count + 1
        end
    end

    return {
        total_errors = total_errors,
        error_types = error_counts,
        recovery_attempts = #ErrorRecovery.recovery_history,
        recovery_success = recovery_success_count,
        recovery_failure = recovery_failure_count,
        recovery_success_rate = #ErrorRecovery.recovery_history > 0 and
                              (recovery_success_count / #ErrorRecovery.recovery_history * 100) or 0,
        performance_report = self:get_performance_report()
    }
end

-- 导出性能监控器
ErrorHandler.PerformanceMonitor = PerformanceMonitor

-- 导出模块
return ErrorHandler
